﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Windows.Forms;
using System.Collections;
using System.IO;
using Command.Model;
using System.Reflection;
using System.Data.Common;
using System.Configuration;
using Sunisoft.IrisSkin;
using Helper;
using Common.Excel;
using System.Diagnostics;

namespace NJGZBTYHXT
{
    public partial class Form1 : Form
    {
        #region 字段与属性

        private SetSkinForm ssf;
        private SkinEngine skin;

        #endregion

        #region 事件

        /// <summary>
        /// 时钟
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timer1_Tick(object sender, EventArgs e)
        {
            labelDate.Text = DateTime.Now.ToString("yyyy年MM月dd日 HH:mm:ss");
        }

        /// <summary>
        /// 退出系统按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripButton8_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        /// <summary>
        /// 窗体关闭事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (MessageBox.Show("您确认要退出“农机购置补贴摇号系统”吗?", "系统提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) != DialogResult.OK)
            {
                e.Cancel = true;
            }
        }

        /// <summary>
        /// 帮助按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripButton7_Click(object sender, EventArgs e)
        {
            //new Form3().ShowDialog(this);
            Help.ShowHelp(this, "help.pdf");
        }

        /// <summary>
        /// 导入数据事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            try
            {
                dataGridView1.Visible = false;

                OpenFileDialog of = new OpenFileDialog();
                of.Title = "打开";
                of.Filter = "Microsoft Excel 97/2000/XP/2003 文件|*.xls|Microsoft Excel 文件|*.xlsx|WPS 表格|*.et|CSV (逗号分割)|*.csv";

                if (of.ShowDialog(this) == DialogResult.OK)
                {
                    try
                    {
                        int sheetCount = 0;

                        DataSet ds = Common.Excel.NPOIHandler.ExcelToDataSet(of.FileName, true, out sheetCount);

                        if (sheetCount > 0)
                        {
                            dataGridView1.DataSource = ds.Tables[0];

                            if (!dataGridView1.Columns.Contains("ID"))
                            {
                                DataGridViewTextBoxColumn c = new DataGridViewTextBoxColumn();
                                c.Name = "ID"; c.HeaderText = "ID";
                                dataGridView1.Columns.Insert(0, c);
                                dataGridView1.Columns["ID"].DisplayIndex = 0;

                                for (int index = 0; index < dataGridView1.Rows.Count; index++)
                                {
                                    dataGridView1.Rows[index].Cells["ID"].Value = index + 1;
                                }
                            }

                            FirstOption.DataGridViewSHC(dataGridView1, "ID,公示地址,开户行,帐号,分档名称,功率,结算单位,经销商,国补总额（元）,省补总额（元）,市补总额（元）,县补总额（元）,总成交价格（元）,打印日期,购机日期,申请结算日期,结算日期,申请结算批次,结算批次,发票号,出厂编号【发动机号】", false, false);

                            FirstOption.OutExcel(dataGridView1, Application.StartupPath + @"\db.xls");

                            LoadText();

                            MessageBox.Show("您成功导入" + dataGridView1.Rows.Count + "条数据。\n请您输入摇号条数开始摇号！", "温馨提示");

                            dataGridView1.Visible = true;
                        }
                        else
                        {
                            MessageBox.Show("没有检测到表数据", "Exception", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message, "Exception", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "导入数据发生异常", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 按条数摇号事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            if (dataGridView1.Rows.Count > 0)
            {
                Atsyh atsyh = new Atsyh();
                atsyh.Dgv = this.dataGridView1;

                if (DialogResult.OK == atsyh.ShowDialog(this))
                {
                    SortedList sl = new SortedList();

                    for (int i = 0; i < atsyh.Jg.Length; i++)
                    {
                        sl.Add(atsyh.Jg[i], atsyh.Jg[i]);
                    }

                    for (int i = sl.Count - 1; i >= 0; i--)
                    {
                        int index = int.Parse(sl.GetByIndex(i).ToString());
                        dataGridView1.Rows.RemoveAt(index);
                    }

                    LoadText();
                }
            }
            else
            {
                NoDataInfo();
            }
        }

        /// <summary>
        /// 按国补摇号
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripButton3_Click(object sender, EventArgs e)
        {
            if (dataGridView1.Rows.Count > 0)
            {
                Agbyh agbyh = new Agbyh();
                agbyh.Text = "国";
                agbyh.ColumnName = "国补总额（元）";
                agbyh.Dgv = this.dataGridView1;

                if (DialogResult.OK == agbyh.ShowDialog(this))
                {
                    if (agbyh.Jg != null)
                    {
                        SortedList sl = new SortedList();

                        for (int i = 0; i < agbyh.Jg.Length; i++)
                        {
                            sl.Add(agbyh.Jg[i], agbyh.Jg[i]);
                        }

                        for (int i = sl.Count - 1; i >= 0; i--)
                        {
                            int index = int.Parse(sl.GetByIndex(i).ToString());
                            dataGridView1.Rows.RemoveAt(index);
                        }
                        LoadText();
                    }
                }
            }
            else
            {
                NoDataInfo();
            }
        }

        /// <summary>
        /// 按省补摇号
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripButton4_Click(object sender, EventArgs e)
        {
            if (dataGridView1.Rows.Count > 0)
            {
                Agbyh agbyh = new Agbyh();
                agbyh.Text = "省";
                agbyh.ColumnName = "省补总额（元）";
                agbyh.Dgv = this.dataGridView1;

                if (DialogResult.OK == agbyh.ShowDialog(this))
                {
                    if (agbyh.Jg != null)
                    {
                        SortedList sl = new SortedList();

                        for (int i = 0; i < agbyh.Jg.Length; i++)
                        {
                            sl.Add(agbyh.Jg[i], agbyh.Jg[i]);
                        }

                        for (int i = sl.Count - 1; i >= 0; i--)
                        {
                            int index = int.Parse(sl.GetByIndex(i).ToString());
                            dataGridView1.Rows.RemoveAt(index);
                        }
                        LoadText();
                    }
                }
            }
            else
            {
                NoDataInfo();
            }
        }

        /// <summary>
        /// 生成Excel
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripButton5_Click(object sender, EventArgs e)
        {
            try
            {
                string path = Application.StartupPath + @"\Excel\";

                if (!Directory.Exists(path)) { Directory.CreateDirectory(path); }

                string filePath = path + DateTime.Now.ToFileTime() + ".xls";

                FirstOption.OutExcel(dataGridView1, filePath);

                if (DialogResult.OK == MessageBox.Show("生成Excel成功，文件路径为：\n" + filePath + "\n是否打开文件？", "温馨提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question))
                {
                    Process.Start(filePath);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Exception", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 清空数据按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripButton6_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("清除后无法恢复，请谨慎操作。确认要清除现有数据库数据吗？", "警告", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                try
                {
                    for (int i = dataGridView1.Rows.Count - 1; i >= 0; i--)
                    {
                        dataGridView1.Rows.RemoveAt(i);
                    }

                    File.Delete(Application.StartupPath + @"\db.xls");

                    LoadText();

                    MessageBox.Show("数据库数据清除完毕.", "提醒", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Exception", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        #endregion

        #region 方法

        /// <summary>
        /// 加载窗体皮肤
        /// </summary>
        public void LoadSkin(object skinName)
        {
            skin.SkinFile = @"Skins\" + skinName.ToString() + ".ssk";
        }

        /// <summary>
        /// 没有数据记录的提示信息
        /// </summary>
        private void NoDataInfo()
        {
            MessageBox.Show("没有发现数据！请先导入基本数据.", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
        }

        /// <summary>
        /// 加载已有数据
        /// </summary>
        private void LoadData()
        {
            try
            {
                string dbFile = Application.StartupPath + @"\" + ConfigurationManager.AppSettings["dbFile"];

                string sheetName = ConfigurationManager.AppSettings["dbFileSheetName"];

                if (File.Exists(dbFile))
                {
                    if (sheetName != "")
                    {
                        dataGridView1.DataSource = Common.Excel.NPOIHandler.ExcelToDataTable(dbFile, sheetName, true);
                        dataGridView1.Columns["ID"].DisplayIndex = 0;

                        FirstOption.DataGridViewSHC(dataGridView1, "id,公示地址,开户行,帐号,分档名称,功率,结算单位,经销商,国补总额（元）,省补总额（元）,市补总额（元）,县补总额（元）,总成交价格（元）,打印日期,购机日期,申请结算日期,结算日期,申请结算批次,结算批次,发票号,出厂编号【发动机号】", false, false);

                        LoadText();
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Exception", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void LoadText()
        {
            int gbze = 0, sbze = 0;

            foreach (DataGridViewRow row in dataGridView1.Rows)
            {
                try
                {
                    int gb = int.Parse(row.Cells["国补总额（元）"].Value.ToString());
                    int sb = int.Parse(row.Cells["省补总额（元）"].Value.ToString());
                    gbze += gb;
                    sbze += sb;
                }
                catch { }
            }

            toolStripStatusLabel1.Text = string.Format("农机购置补贴摇号系统  总条数:{0}  国补总额(元):{1}  省补总额(元):{2}", dataGridView1.Rows.Count, gbze, sbze);
        }

        #endregion

        public Form1()
        {
            InitializeComponent();

            skin = new SkinEngine();

            //获取皮肤设置
            string isSkin = System.Configuration.ConfigurationManager.AppSettings["skin"];

            if (isSkin.ToLower().Equals("true"))
            {
                LoadSkin(System.Configuration.ConfigurationManager.AppSettings["skinName"]);
            }
        }

        private void 候选设置ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Form4 f4 = new Form4();
            f4.Dgv = dataGridView1;
            f4.ShowDialog(this);
        }

        private void 主题ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (ssf.ShowDialog(this) == DialogResult.OK)
            {
                ConfigurationManager.AppSettings.Set("skinName", ssf.SkinName.ToString());
                ConfigurationManager.RefreshSection("appSettings");
                LoadSkin(ssf.SkinName);
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //开启时钟
            timer1.Enabled = true;
            notifyIcon1.Text = this.Text;
            ssf = new SetSkinForm();
            //加载数据
            //LoadData();
        }
    }
}
